package com.dz.db.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.baomidou.mybatisplus.entity.TableInfo;
import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
import com.dz.db.IdGenerator;

public class IdGeneratorImpl implements IdGenerator {

	private final JdbcTemplate jdbcTemplate;

	public IdGeneratorImpl(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public Long generatorId(String name) {
		String sql = "UPDATE ticket_mutex SET value=LAST_INSERT_ID(value+1) WHERE name=?";
		jdbcTemplate.update(sql, name);
		return jdbcTemplate.queryForObject("SELECT LAST_INSERT_ID()", new RowMapper<Long>() {
			public Long mapRow(ResultSet rs, int arg1) throws SQLException {
				return rs.getLong(1);
			}
		});
	}

	@Override
	public Long generatorId(Class<?> entityClass) {
		TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
		String name = entityClass.getName();
		if (tableInfo != null) {
			name = tableInfo.getTableName();
		}
		return generatorId(name);
	}
}
